package cn.tedu.service.impl;

import cn.tedu.constant.WxSelfConstant;
import cn.tedu.service.IWxService;
import cn.tedu.util.HttpClientUtil;
import cn.tedu.util.SHA1;
import cn.tedu.vo.AccessTokenBean;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class WxServiceImpl implements IWxService {
    @Value("${wx.token}")
    private String token ;

    @Value("${wx.appID}")
    private String appID;
    @Value("${wx.appsecret}")
    private String appSecret;
    @Value("${wx.baseUrl}")
    private String baseUrl;
    private AccessTokenBean accessTokenBean;
    @Override
    public void createMenu() {
        String redirectUrl = WxSelfConstant.OAUTH2_AUTHORIZE.replace("APPID", appID)
                .replace("REDIRECT_URI", baseUrl + "/wx/getCode")
                .replace("SCOPE", "snsapi_userinfo");
        // 准备菜单
        WxMenu  wxMenu = new WxMenu();
        // 准备一级按钮S
        List<WxMenuButton> firstButtons=new ArrayList<>();
        // 准备一级按钮
        WxMenuButton wxMenuButton = new WxMenuButton();
        wxMenuButton.setType(WxConsts.MenuButtonType.VIEW);
        wxMenuButton.setName("百度去吧您");
        wxMenuButton.setUrl(redirectUrl);
        firstButtons.add(wxMenuButton);
        wxMenu.setButtons(firstButtons);
        // 准备二级按钮
        String url = WxSelfConstant.CREATE_MENU_URL.replace("ACCESS_TOKEN",getAccessToken());
        // 准备路径参数
        String menuJson = wxMenu.toJson();
        // 发送请求
        String s = HttpClientUtil.doPostJson(url, menuJson);
        System.out.println(s);
    }

    @Override
    public String getAccessToken() {
        if(accessTokenBean==null || accessTokenBean.isExpired()) {
            synchronized (this) {
                if (accessTokenBean == null || accessTokenBean.isExpired()) {
                    refreshToken();
                }
            }
        }
        return accessTokenBean.getAccessToken();
    }



    private void refreshToken(){
        // 准备参数
        String url= WxSelfConstant.ACCESS_TOKEN_URL
                .replace("APPID",appID)
                .replace("APPSECRET",appSecret);
        // 发送请求
        String s = HttpClientUtil.doGet(url);
        JSONObject jsonObject = JSON.parseObject(s);
        String accessToken = (String)jsonObject.get("access_token");
        Long expiresTime = jsonObject.getLong("expires_in");
        // 保存accesstoken
        accessTokenBean = new AccessTokenBean(appID,appSecret,accessToken,expiresTime);
        System.out.println(accessTokenBean.getAccessToken());
    }

    @Override
    public String checkWx(String signature, String timestamp, String nonce, String echostr) {
        //1）将token、timestamp、nonce三个参数进行字典序排序
        String [] strs = {token,timestamp,nonce};
        Arrays.sort(strs);
       // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder builder = new StringBuilder();
        for (String str : strs) {
            builder.append(str);
        }
        String selfSignature = SHA1.encode(builder.toString());
        //3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if(selfSignature.equals(signature)){
            return echostr;
        }
        return null;
    }


}
